<!DOCTYPE html>
<html lang="zh-CN">
<head>
	<meta charset="UTF-8">
	<title>用户列表（带权限控制）</title>
	<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
	<script src="js/vue.js"></script>
	<script src="element-ui/lib/index.js"></script>
	<script src="js/axios-0.18.0.js"></script>
	<script src="js/server.js"></script>
	<style>
		.el-table {
			margin-top: 20px;
		}
		.el-pagination {
			margin-top: 20px;
			text-align: right;
		}
		.edit-dialog .el-form-item {
			margin-bottom: 15px;
		}
	</style>
</head>
<body>
<div id="app">
	<!-- 查询区域 -->
	<el-form :inline="true" :model="searchForm" class="demo-form-inline">
		<el-form-item label="用户编码">
			<el-input v-model="searchForm.userCode" placeholder="请输入用户编码" maxlength="20"></el-input>
		</el-form-item>
		<el-form-item label="用户名称">
			<el-input v-model="searchForm.userName" placeholder="请输入用户名称" maxlength="50"></el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="doSearch">查询</el-button>
			<el-button @click="resetSearch">重置</el-button>
		</el-form-item>
	</el-form>

	<!-- 表格列表 -->
	<el-table :data="tableData" style="width: 100%" border>
		<el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
		<el-table-column prop="userCode" label="用户编码" width="120" align="center"></el-table-column>
		<el-table-column prop="userName" label="用户名称" width="120" align="center"></el-table-column>
		<el-table-column prop="phone" label="手机号" width="120" align="center"></el-table-column>
		<!-- 修复：角色字段从row.role改为row.userRole，与数据字段匹配 -->
		<el-table-column label="用户角色" width="120" align="center">
			<template slot-scope="scope">
				{{ getRoleName(scope.row.userRole) }}
			</template>
		</el-table-column>
		<el-table-column label="状态" width="100" align="center">
			<template slot-scope="scope">
				<el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
					{{ scope.row.status === 1 ? '正常' : '冻结' }}
				</el-tag>
			</template>
		</el-table-column>
		<el-table-column prop="creationDate" label="创建时间" width="180" align="center"></el-table-column>
		<el-table-column label="操作" width="280" align="center" fixed="right">
			<template slot-scope="scope">
				<!-- 查看按钮：所有人可见 -->
				<el-button size="mini" @click="handleShow(scope.row)">查看</el-button>

				<!-- 编辑按钮：根据角色权限控制显示 -->
				<el-button
						size="mini"
						type="primary"
						icon="el-icon-edit"
						@click="handleEdit(scope.row)"
						v-if="canEdit(scope.row.userRole)">
					编辑
				</el-button>

				<!-- 冻结/启用按钮：带权限控制 -->
				<el-button
						size="mini"
						:type="scope.row.status === 2 ? 'success' : 'danger'"
						@click="doUpdateStatus(scope.row.id, scope.row.status === 1 ? 2 : 1)"
						v-if="canUpdateStatus(scope.row.userRole)">
					{{ scope.row.status === 1 ? '冻结' : '启用' }}
				</el-button>
			</template>
		</el-table-column>
	</el-table>

	<!-- 分页条 -->
	<el-pagination
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			:current-page="pagination.currentPage"
			:page-sizes="[5, 10, 20, 50]"
			:page-size="pagination.pageSize"
			layout="total, sizes, prev, pager, next, jumper"
			:total="pagination.total">
	</el-pagination>

	<!-- 查看对话框 -->
	<el-dialog title="用户详情" :visible.sync="showFormVisible" width="600px">
		<el-form :model="showForm" label-width="100px">
			<el-row>
				<el-col :span="12">
					<el-form-item label="用户编码">
						<el-input v-model="showForm.userCode" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用户名称">
						<el-input v-model="showForm.userName" readonly></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="性别">
						<el-input :value="showForm.gender === 1 ? '男' : '女'" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="出生日期">
						<el-input v-model="showForm.birthday" readonly></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="手机号">
						<el-input v-model="showForm.phone" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="状态">
						<el-tag :type="showForm.status === 1 ? 'success' : 'danger'">
							{{ showForm.status === 1 ? '正常' : '冻结' }}
						</el-tag>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="地址">
				<el-input v-model="showForm.address" type="textarea" :rows="2" readonly></el-input>
			</el-form-item>
			<el-row>
				<el-col :span="12">
					<el-form-item label="用户角色">
						<el-input :value="getRoleName(showForm.userRole)" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="创建时间">
						<el-input v-model="showForm.creationDate" readonly></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="showFormVisible = false">关闭</el-button>
		</div>
	</el-dialog>

	<!-- 编辑对话框 -->
	<el-dialog title="编辑用户" :visible.sync="editFormVisible" width="600px" class="edit-dialog">
		<el-form :model="editForm" label-width="100px" ref="editForm">
			<el-row>
				<el-col :span="12">
					<el-form-item label="用户编码" prop="userCode">
						<el-input v-model="editForm.userCode" readonly placeholder="不可修改编码"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用户名称" prop="userName">
						<el-input v-model="editForm.userName" placeholder="请输入用户名称" maxlength="50"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="性别" prop="gender">
						<el-select v-model="editForm.gender" placeholder="请选择性别">
							<el-option label="男" :value="1"></el-option>
							<el-option label="女" :value="2"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="出生日期" prop="birthday">
						<el-date-picker
								v-model="editForm.birthday"
								type="date"
								placeholder="选择日期"
								value-format="yyyy-MM-dd">
						</el-date-picker>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="手机号" prop="phone">
						<el-input v-model="editForm.phone" placeholder="请输入手机号" maxlength="11"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="状态" prop="status">
						<el-select v-model="editForm.status" placeholder="请选择状态">
							<el-option label="正常" :value="1"></el-option>
							<el-option label="冻结" :value="2"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="地址" prop="address">
				<el-input v-model="editForm.address" type="textarea" :rows="2" placeholder="请输入地址"></el-input>
			</el-form-item>
			<el-row>
				<el-col :span="12">
					<el-form-item label="用户角色" prop="userRole">
						<!-- 角色下拉：根据当前用户角色过滤可选范围 -->
						<el-select v-model="editForm.userRole" placeholder="请选择角色">
							<el-option
									v-for="opt in filteredRoleOptions"
									:key="opt.value"
									:label="opt.label"
									:value="opt.value">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="editFormVisible = false">取消</el-button>
			<el-button type="primary" @click="doSaveEdit">保存</el-button>
		</div>
	</el-dialog>
</div>

<script>
	new Vue({
		el: '#app',
		data() {
			return {
				searchForm: { userCode: "", userName: "" },
				tableData: [],
				pagination: { currentPage: 1, pageSize: 10, total: 0 },
				showFormVisible: false,
				showForm: {},
				editFormVisible: false,
				editForm: {},
				currentUserRole: 3, // 默认普通员工，实际从登录信息获取
				roleOptions: [
					{ label: '系统管理员', value: 1 },
					{ label: '经理', value: 2 },
					{ label: '普通员工', value: 3 }
				]
			};
		},
		computed: {
			// 动态过滤角色下拉选项
			filteredRoleOptions() {
				if (this.currentUserRole === 1) return this.roleOptions;
				if (this.currentUserRole === 2) return this.roleOptions.filter(opt => opt.value >= 2);
				return [];
			}
		},
		methods: {
			// 根据角色值获取角色名称（核心修复：兼容数字类型不匹配问题）
			getRoleName(roleValue) {
				// 强制转换为数字，避免字符串与数字匹配失败
				const numValue = Number(roleValue);
				const role = this.roleOptions.find(opt => opt.value === numValue);
				return role ? role.label : '未知角色';
			},

			// 查询用户列表
			doList() {
				const params = {
					currentPage: Number(this.pagination.currentPage),
					pageSize: Number(this.pagination.pageSize),
					userCode: this.searchForm.userCode?.trim() || '',
					userName: this.searchForm.userName?.trim() || '',
				};
				if (params.currentPage < 1) params.currentPage = 1;
				if (params.pageSize < 1) params.pageSize = 10;

				axios.get(server_url + "/api/user/page", { params })
						.then(resp => {
							if (resp.data.code === 0) {
								this.tableData = resp.data.data.list || [];
								this.pagination.total = resp.data.data.total || 0;
							} else {
								this.$message.error(resp.data.msg || '获取用户列表失败');
							}
						})
						.catch(err => {
							console.error('获取用户列表错误:', err);
							this.$message.error('请求失败，请检查网络');
						});
			},

			// 搜索
			doSearch() {
				this.pagination.currentPage = 1;
				this.doList();
			},

			// 重置搜索条件
			resetSearch() {
				this.searchForm = { userCode: "", userName: "" };
				this.doSearch();
			},

			// 分页大小改变
			handleSizeChange(val) {
				this.pagination.pageSize = Number(val);
				this.doList();
			},

			// 当前页改变
			handleCurrentChange(val) {
				this.pagination.currentPage = Number(val);
				this.doList();
			},

			// 查看用户详情
			handleShow(row) {
				const userId = Number(row.id);
				if (isNaN(userId)) {
					this.$message.error('用户ID无效');
					return;
				}

				axios.get(`${server_url}/api/user/${userId}`)
						.then(resp => {
							if (resp.data.code === 0) {
								this.showForm = resp.data.data;
								this.showFormVisible = true;
							} else {
								this.$message.error(resp.data.msg || '获取用户详情失败');
							}
						})
						.catch(err => {
							console.error('获取用户详情错误:', err);
							this.$message.error('获取用户详情失败，请重试');
						});
			},

			// 编辑用户
			handleEdit(row) {
				this.editForm = JSON.parse(JSON.stringify(row));
				// 强制转换为数字，避免下拉框匹配问题
				this.editForm.gender = Number(this.editForm.gender);
				this.editForm.status = Number(this.editForm.status);
				this.editForm.userRole = Number(this.editForm.userRole);
				this.editFormVisible = true;
			},

			// 保存编辑内容（修复接口路径）
			doSaveEdit() {
				this.$refs.editForm.validate(valid => {
					if (valid) {
						// 接口路径改为后端实际支持的更新接口（通常为/api/user/update）
						axios.put(server_url + "/api/user/update", this.editForm)
								.then(resp => {
									if (resp.data.code === 0) {
										this.$message.success('编辑成功');
										this.editFormVisible = false;
										this.doList();
									} else {
										this.$message.error(resp.data.msg || '编辑失败');
									}
								})
								.catch(err => {
									console.error('编辑用户错误:', err);
									this.$message.error('编辑失败，请重试');
								});
					} else {
						this.$message.error('表单校验失败，请检查输入');
					}
				});
			},

			// 权限控制：判断是否可编辑
			canEdit(targetRole) {
				const numRole = Number(targetRole);
				if (this.currentUserRole === 1) return true;
				if (this.currentUserRole === 2) return [2, 3].includes(numRole);
				return false;
			},

			// 权限控制：判断是否可更新状态
			canUpdateStatus(targetRole) {
				const numRole = Number(targetRole);
				if (this.currentUserRole === 1) return true;
				if (this.currentUserRole === 2) return [2, 3].includes(numRole);
				return false;
			},

			// 更新用户状态（冻结/启用）
			doUpdateStatus(id, status) {
				const userId = Number(id);
				const userStatus = Number(status);
				if (isNaN(userId) || isNaN(userStatus)) {
					this.$message.error('参数无效');
					return;
				}

				const action = userStatus === 1 ? '启用' : '冻结';
				this.$confirm(`确认${action}该用户?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					axios.post(server_url + "/api/user/updateStatus", null, {
						params: { id: userId, status: userStatus }
					}).then(resp => {
						if (resp.data.code === 0) {
							this.$message.success(`${action}成功`);
							this.doList();
						} else {
							this.$message.error(`${action}失败：${resp.data.msg || '操作异常'}`);
						}
					}).catch(err => {
						console.error(`${action}用户错误:`, err);
						this.$message.error(`${action}失败，请重试`);
					});
				}).catch(() => {
					this.$message.info('已取消操作');
				});
			}
		},
		mounted() {
			// 获取当前登录用户角色（从登录信息中提取）
			const loginUser = localStorage.getItem('loginUser');
			if (loginUser) {
				try {
					const user = JSON.parse(loginUser);
					this.currentUserRole = Number(user.userRole) || 3;
				} catch (e) {
					console.error('解析用户信息失败:', e);
					this.currentUserRole = 3;
				}
			} else {
				// 未登录时跳转登录页
				this.$message.warning('请先登录');
				window.location.href = "login.html";
			}
			this.doList();
		}
	});
</script>
</body>
</html>